<template>
  <div class="client-wrap">
    <div class="head">
      <span>用户管理</span>
    </div>
    <div class="head-list">
      <div @click="fastSearch">
        <img src="../assets/images/fast_search.png" />
        <div>
          <span>快捷查询</span>
          <span style="font-size: 18px;">
            {{searchDate[0] || '--'}}至{{searchDate[1] || '--'}}
          </span>
          <span style="font-size: 30px; font-weight: bold;">
            {{searchNum || '--'}}
            <span>人</span>
          </span>
        </div>
      </div>
      <div>
        <img src="../assets/images/today_num.png" />
        <div>
          <span>今日新增</span>
          <span>
            {{consumeData.membershipToday}}
            <span>人</span>
          </span>
        </div>
      </div>
      <div>
        <img src="../assets/images/month_num.png" />
        <div>
          <span>本月新增(至今)</span>
          <span>
            {{consumeData.thisMonthNumber}}
            <span>人</span>  
          </span>
        </div>
      </div>
      <div>
        <img src="../assets/images/total_num.png" />
        <div>
          <span>总用户数</span>
          <span>
            {{consumeData.numberOfMembers}}
            <span>人</span>
          </span>
        </div>
      </div>
    </div>
    <div class="search-con m-t-b">
      <el-select v-model="searchType">
        <el-option label="昵称" :value="1"></el-option>
        <el-option label="用户编号" :value="2"></el-option>
      </el-select>
      <el-input v-model="search" clearable @input="clearSearch" @keypress.native.enter="handleSearch"/>
      <el-button @click="handleSearch" type="primary">搜索</el-button>
    </div>
    <el-tabs type="border-card" style="margin-top: 10px;">
      <el-tab-pane label="健康尺">
        <el-table
          class="m-t-b"
          :data="tableData"
          v-loading="loading"
          stripe
          border
        >
          <el-table-column
            prop="id"
            label="用户编号"
          >
          </el-table-column>
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img
                v-if="scope.row.headPortrait"
                :src="scope.row.headPortrait"
                style="width: 60px; height: 60px; border-radius: 50%;"
              />
              <span v-if="!scope.row.headPortrait">暂无头像</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
          >
          </el-table-column>
          <el-table-column
            prop="createDate"
            label="创建时间"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            width="150">
            <template slot-scope="scope">
              <el-button @click="userInfo(scope.row)" type="text" size="small">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handlePagi"
          :total="total">
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="消防">
        <el-table
          class="m-t-b"
          :data="firemanList"
          v-loading="firemanLoading"
          stripe
          border
        >
          <el-table-column
            prop="id"
            label="用户编号"
          >
          </el-table-column>
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img
                v-if="scope.row.headPortrait"
                :src="scope.row.headPortrait"
                style="width: 60px; height: 60px; border-radius: 50%;"
              />
              <span v-if="!scope.row.headPortrait">暂无头像</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
          >
          </el-table-column>
          <el-table-column
            prop="createDate"
            label="创建时间"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            width="150">
            <template slot-scope="scope">
              <el-button @click="userInfo(scope.row)" type="text" size="small">
                查看
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="setSportsAuthority(scope.row)"
              >设置权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleFiremanPagi"
          :total="firemanTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    
    <el-dialog title="快捷查询用户数量" :visible.sync="showSearchDialog">
      <el-date-picker
        v-model="searchDate"
        type="daterange"
        align="right"
        unlink-panels
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button
        style="margin-left: 15px;"
        type="primary"
        @click="handleFastSearch"
        :disabled="!searchDate"
        :loading="fastLoading"
      >
        <i class="el-icon-search"></i>
        搜索
      </el-button>
      <h2>
        {{searchDate[0] || '--'}}至{{searchDate[1] || '--'}}:
        <span style="font-size: 25px; font-weight: bold;">{{searchNum || '--'}}</span>
        人
      </h2>
    </el-dialog>

    <el-dialog title="设置该用户管理的班级(体育)" :visible.sync="showSportsDialog">
      <el-form inline>
        <el-form-item label="年级" v-if="false">
          <el-input v-model="sportsGrade" />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="sportsClass">
            <el-option
              v-for="(item, index) in classRange"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSportsClass" :loading="sportLoading">保存</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="classList" border stripe v-loading="classLoding">
        <el-table-column label="年级" prop="grade"></el-table-column>
        <el-table-column label="班级" prop="grades"></el-table-column>
        <el-table-column label="创建时间" prop="createDate"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" circle icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import { getWecharUserList } from '../api';
import { formatDate } from '../util';
import {
  getUserConsume,
  getUserNumByDate,
  giveFiremanClass,
  getFiremanClass,
  deleteFiremanClass
} from '../api/version2';

export default {
  name: 'ClientUser',
  data () {
    const classRange = Array(100).fill(1).map((item, index) => (index + 1) + '班');
    classRange.unshift('干部');
    return {
      classRange,
      sportsGrade: '',
      sportsClass: '',
      search: '',
      loading: false,
      searchDate: '',
      pageSize: 10,
      total: 0,
      showSearchDialog: false,
      showSportsDialog: false,
      sort: {
        date: 'descending'
      },
      searchNum: '',
      consumeData: {
        membershipToday: '',
        numberOfMembers: '',
        thisMonthNumber: ''
      },
      userId: '',
      searchType: 1,
      tableData: [],
      fastLoading: false,
      userType: 1,
      firemanList: [],
      firemanLoading: false,
      firemanTotal: 0,
      sportLoading: false,
      classLoding: false,
      classList: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    clearSearch () {
      if (!this.search) {
        this.fetchUserList(1, null, null, 1);
        this.fetchUserList(1, null, null, 2)
      }
    },
    handleDelete (row) { // 删除
      this.$confirm(`确定该班级吗?删除后该用户不再管理该班级`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        deleteFiremanClass(row.id)
        .then(res => {
          this.$message.success('删除成功');
          this.fetchFiremanClass()
        })
        .catch(e => {})
      })
      .catch(err => {})
    },
    setSportsAuthority (row) { // 设置体适能权限
      this.userId = row.id;
      this.sportsGrade = '';
      this.sportsClass = '';
      this.classList = [];
      this.fetchFiremanClass();
      this.showSportsDialog = true
    },
    saveSportsClass () { // 保存体育班级
      this.sportLoading = true;
      giveFiremanClass({
        userId: this.userId,
        grade: this.sportsGrade,
        grades: this.sportsClass
      })
      .then(res => {
        this.sportLoading = false;
        this.$message.success('操作成功');
        this.fetchFiremanClass()
      })
      .catch(e => {
        this.sportLoading = false
      })
    },
    fetchFiremanClass () { // 查询绑定班级
      this.classLoding = true;
      getFiremanClass(this.userId)
      .then(res => {
        this.classLoding = false;
        let list = res.data.data || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'zh:')
        });
        this.classList = list
      })
      .catch(e => {
        this.classLoding = false
      })
    },
    handleSearch () {
      if (!this.$checkAuth('canSearch')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (!this.search.trim()) {
        this.search = ''
        return this.$message.error('请输入搜索内容!')
      };
      if (this.searchType === 1) { // 按昵称搜索
        this.fetchUserList(1, this.search, null, 1);
        this.fetchUserList(1, this.search, null, 2)
      } else if (this.searchType === 2) { // 按编号搜索
        this.fetchUserList(1, null, this.search, 1);
        this.fetchUserList(1, null, this.search, 2)
      }
    },
    fetchUserConsume () { // 获取用户统计
      getUserConsume()
      .then(res => {
        let obj = res.data.data;
        this.consumeData = obj
      })
      .catch(e => {

      })
    },
    userInfo (info) {
      console.log(info);
      if (!this.$checkAuth('canSeeDetail')) {
        return this.$message.error('暂无对应操作权限!')
      };
      sessionStorage.setItem('info', JSON.stringify(info));
      this.$router.push('/user/info')
    },
    handlePagi (page) {
      if (this.search.trim()) {
        if (this.searchType === 1) { // 按昵称搜索
          this.fetchUserList(page, this.search, null, 1)
        } else if (this.searchType === 2) { // 按编号搜索
          this.fetchUserList(page, null, this.search, 1)
        }
      } else {
        this.fetchUserList(page, null, null, 1)
      }
    },
    handleFiremanPagi (page) { // 消防员分页
      if (this.search.trim()) {
        if (this.searchType === 1) { // 按昵称搜索
          this.fetchUserList(page, this.search, null, 2)
        } else if (this.searchType === 2) { // 按编号搜索
          this.fetchUserList(page, null, this.search, 2)
        }
      } else {
        this.fetchUserList(page, null, null, 2)
      }
    },
    fastSearch () { // 快捷搜索
      this.showSearchDialog = true
    },
    fetchUserList (index, name, id, type) {
      name = name || null;
      id = id || null;
      this[type == 1 ? 'loading' : 'firemanLoading'] = true;
      getWecharUserList({
        index: index,
        count: this.pageSize,
        queryParam: {
            nickname: name,
            fitbarOpenId: id,
            loginType: type
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this[type == 1 ? 'total' : 'firemanTotal'] = res.data.data.totalRecord;
          for (let i = 0; i < list.length; i ++) {
            list[i].createDate = formatDate(list[i].createDate, 'ZH')
          };
          this[type == 1 ? 'tableData' : 'firemanList'] = list
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        };
        this[type == 1 ? 'loading' : 'firemanLoading'] = false
      })
      .catch(e => {
        this.$message.error('网络异常!');
        this[type == 1 ? 'loading' : 'firemanLoading'] = false
      })
    },
    handleFastSearch () { // 快捷搜索
      this.fetchUserNumByDate()
    },
    fetchUserNumByDate () { // 快捷搜索
      this.fastLoading = true;
      const s = this.searchDate[0] + ' 00:00:00';
      const e = this.searchDate[1] + ' 23:59:59';
      getUserNumByDate(s, e)
      .then(res => {
        this.fastLoading = false;
        this.searchNum = res.data.data
      })
      .catch(e => {
        this.fastLoading = false
      })
    }
  },
  created () {
    this.fetchUserList(1, null, null, 1);
    this.fetchUserList(1, null, null, 2);
    this.fetchUserConsume()
  }
}
</script>
<style lang="scss">
  .client-wrap {
    height: 100%;
    padding: 40px;
    .search-con {
      display: flex;
    }
  }
  .head-list {
    display: flex;
    margin-top: 20px;
    justify-content: space-between;
    & > div {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 340px!important;
      height: 120px;
      border-radius: 4px;
      box-shadow: 0 0 10px #ccc;
      cursor: pointer;
      img {
        margin-right: 20px;
        width: 80px;
        height: 80px;
      }
      & > div > span {
        display: block;
        font-weight: bold;
        &:nth-of-type(1) {
          font-size: 20px;
        }
        &:nth-of-type(2) {
          font-size: 30px;
          span {
            font-size: 20px;
            color: #666;
          }
        }
      }
    }
  }
</style>
